﻿using System;
using System.Collections.Generic;

namespace Quail.Silverlight
{
    /// <summary>
    /// A standard silverlight control
    /// </summary>
    /// <typeparam name="T">Control class to use</typeparam>
    public class SlvControlList<T> : SlvControl where T : SlvControl, new()
    {
        private readonly List<T> _controls = new List<T>();

        /// <summary>
        /// Initializes a new instance of the <see cref="SlvControlList{T}"/> class.
        /// </summary>
        /// <param name="container">The container for the control.</param>
        /// <param name="selector">The selector.</param>
        public SlvControlList(SlvControlContainer container, string selector)
            : base(container, selector)
        {
        }

        /// <summary>
        /// Gets the count of controls in the control list
        /// </summary>
        public int Count
        {
            get
            {
                var task = BeginTask("Count");
                try
                {
                    int result;

                    var js = @"var ct = " + SlvPage.Selector + "." + ObjectSelector + ";" +
                             @"if (ct == null) 0; else " +
                             @"if (ct.length == undefined) 1; else " +
                             @"ct.length;";

                    var str = SlvPage.GetEval(js);

                    int.TryParse(str, out result);

                    task.Finish(result.ToString());

                    return result;
                }
                catch (Exception e)
                {
                    task.Finish(e);
                    throw;
                }
            }
        }

        /// <summary>
        /// Gets the control for the given index
        /// </summary>
        /// <param name="index">the index of the control</param>
        public T this[int index]
        {
            get
            {
                for (var i = _controls.Count; i <= index; i++)
                {
                    var newt = new T
                                   {
                                       ParentControl = this.ParentControl,
                                       MySelector = this.MySelector + ":eq(" + i + ")"
                                   };

                    _controls.Add(newt);
                }

                return _controls[index];
            }
        }
    }
}
